package com.rivues.util.function.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.aviator.AviatorEvaluator;
import com.rivues.util.function.Function;

public class DateFunction implements Function {

	@Override
	public Object excute(String functionstr) {
		// TODO Auto-generated method stub
		String function = functionstr;
		try {
			Date day_date = null;
			Date month_date = null;
			Date year_date = null;
			Date date = new Date();
			if(functionstr==null)return functionstr;
			functionstr = functionstr.replace("date(", "");
			functionstr = functionstr.replace(")", "");
			String[] params = functionstr.split(",");
			if(params.length<3){//一共三个参数，第一个年，第二个月，第三个日，第四个是日期格式，如果参数不够则视为无效函数，直接返回
				return functionstr;
			}
			
			if(params[2].indexOf("d")>-1||params[2].indexOf("D")>-1){//处理天
				date.setDate(this.getDaysParam(params[2], date));
			}
			
			if(params[1].indexOf("m")>-1||params[1].indexOf("M")>-1){//处理月
				date.setMonth(this.getDaysParam(params[1], date));
			}
			
			if(params[0].indexOf("y")>-1||params[0].indexOf("Y")>-1){//处理年
				date.setYear(this.getDaysParam(params[0], date));
			}
			SimpleDateFormat sdf = null; 
			if(params.length==4){//处理年
				sdf = new SimpleDateFormat(params[3]);
			}else{
				sdf = new SimpleDateFormat("yyyy-MM-dd");
			}
			return sdf.format(date);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("日期转换失败！");
			return function;
		}
	}
	public static void main(String[] args) throws Exception{
		DateFunction fun = new DateFunction();
		System.out.println(fun.excute("function:date(y-1,m-11,d-6,yyyy年MM月dd日)"));
	}
	
	
	public Integer getDaysParam(String text,Date date){
		Map<String,Object>  context = new HashMap<String,Object>();
		context.put("D", date.getDate()) ;
		context.put("d", date.getDate()) ;
		context.put("M", date.getMonth()) ;
		context.put("m", date.getMonth()) ;
		context.put("Y", date.getYear()) ;
		context.put("y", date.getYear()) ;
    	return Integer.parseInt(AviatorEvaluator.execute(text , context).toString()) ;
	}
	


}
